package com.kqb.sgpicturebackend.manager.upload;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.kqb.sgpicturebackend.common.ErrorCode;
import com.kqb.sgpicturebackend.config.CosClientConfig;
import com.kqb.sgpicturebackend.exception.BusinessException;
import com.kqb.sgpicturebackend.manager.CosManager;
import com.kqb.sgpicturebackend.model.bo.UploadPictureResult;
import com.kqb.sgpicturebackend.utils.ThrowUtils;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/4/28 14:08
 * @description: 通用文件上传下载管理
 */
@Slf4j
@Service
public abstract class PictureUploadTemplate {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * 获取原始文件名
     *
     * @param inputSource
     * @return
     */
    public abstract String getOriginalFilename(Object inputSource);

    /**
     * 处理文件
     *
     * @param inputSource
     * @param tempFile
     */
    public abstract void processFile(Object inputSource, File tempFile);

    /**
     * 校验图片参数
     *
     * @param inputSource
     */
    public abstract void validatePicture(Object inputSource);


    /**
     * 上传图片到cos
     *
     * @param inputSource
     * @param uploadPathPrefix
     * @return
     */
    public UploadPictureResult uploadPicture(Object inputSource, String uploadPathPrefix) {
        //校验文件参数
        validatePicture(inputSource);
        //得到文件名
        String originalFilename = getOriginalFilename(inputSource);
        //得到文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);

        String uuid = UUID.randomUUID().toString(true);

        String fileName = String.format("%s_%s.%s", DateUtil.format(new Date(System.currentTimeMillis()), "yyyyMMdd"), uuid, suffix);
        //文件路径
        String uploadFilePath = String.format("/%s/%s", uploadPathPrefix, fileName);

        File tempFile = null;
        try {
            tempFile = File.createTempFile(uploadFilePath, null);
            //下载文件到本地
            processFile(inputSource, tempFile);

            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadFilePath, tempFile);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();

            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + uploadFilePath);
            uploadPictureResult.setName(FileUtil.mainName(originalFilename));
            uploadPictureResult.setPicSize(FileUtil.size(tempFile));
            uploadPictureResult.setPicWidth(imageInfo.getWidth());
            uploadPictureResult.setPicHeight(imageInfo.getHeight());
            uploadPictureResult.setPicScale(NumberUtil.round(imageInfo.getWidth() * 1.0 / imageInfo.getHeight(), 2).doubleValue());
            uploadPictureResult.setPicFormat(imageInfo.getFormat());

            return uploadPictureResult;

        } catch (Exception e) {
            log.error("图片上传到储存桶失败:{}", uploadFilePath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");

        } finally {
            if (tempFile != null) {
                boolean delete = tempFile.delete();
                if (!delete) {
                    log.error("临时文件删除失败:{}", uploadFilePath);
                }
            }
        }
    }


}
